package com.heixiu.gallery2

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import kotlinx.android.synthetic.main.gallery_item.view.*
import kotlinx.android.synthetic.main.gallery_load_more.view.*

class GalleryAdapter(val galleryViewModel: GalleryViewModel) : ListAdapter<PhotoItem, GalleryViewHolder>(DIFFCALLBACK) {
    var requestState = GALLERY_REQUEST_NORMAL

    companion object {
        const val NORMAL_TYPE = 0
        const val LOAD_MORE_TYPE = 1
    }

    object DIFFCALLBACK : DiffUtil.ItemCallback<PhotoItem>() {
        override fun areItemsTheSame(oldItem: PhotoItem, newItem: PhotoItem): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: PhotoItem, newItem: PhotoItem): Boolean {
            return oldItem == newItem
        }
    }

    override fun getItemCount(): Int {
        return super.getItemCount() + 1
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == itemCount - 1) LOAD_MORE_TYPE else NORMAL_TYPE
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GalleryViewHolder {
        val holder: GalleryViewHolder
        if (viewType == NORMAL_TYPE) {
            holder = GalleryViewHolder(
                LayoutInflater.from(parent.context).inflate(
                    R.layout.gallery_item,
                    parent,
                    false
                )
            )
            holder.itemView.setOnClickListener {
                Bundle().apply {
                    putInt("current_position", holder.bindingAdapterPosition)
                    putParcelableArrayList("photo_list", ArrayList(currentList))
                    val navController = holder.itemView.findNavController()
                    navController.navigate(R.id.gallery_to_photos, this)
                }
            }
        } else {
            holder = GalleryViewHolder(
                LayoutInflater.from(parent.context).inflate(
                    R.layout.gallery_load_more,
                    parent,
                    false
                ).also {
                    (it.layoutParams as StaggeredGridLayoutManager.LayoutParams).isFullSpan = true
                    it.setOnClickListener {itemView->
                        itemView.textViewGalleryLoadMoreNoData.visibility = View.GONE
                        itemView.progressBarGalleryLoadMore.visibility = View.VISIBLE
                        itemView.textViewGalleryLoadMore.visibility = View.VISIBLE
                        galleryViewModel.fetchData()
                    }
                }
            )
        }
        return holder
    }

    override fun onBindViewHolder(holder: GalleryViewHolder, position: Int) {
        if (position == itemCount - 1) {
            with(holder.itemView) {
                when(requestState) {
                    GALLERY_REQUEST_NORMAL -> {
                        isClickable = false
                        textViewGalleryLoadMoreNoData.visibility = View.GONE
                        progressBarGalleryLoadMore.visibility = View.VISIBLE
                        textViewGalleryLoadMore.visibility = View.VISIBLE
                    }
                    GALLERY_REQUEST_NO_DATA -> {
                        isClickable = false
                        progressBarGalleryLoadMore.visibility = View.GONE
                        textViewGalleryLoadMore.visibility = View.GONE
                        textViewGalleryLoadMoreNoData.text = "加载完毕"
                        textViewGalleryLoadMoreNoData.visibility = View.VISIBLE
                    }
                    GALLERY_REQUEST_NETWORK_ERROR -> {
                        isClickable = true
                        progressBarGalleryLoadMore.visibility = View.GONE
                        textViewGalleryLoadMore.visibility = View.GONE
                        textViewGalleryLoadMoreNoData.text = "网络故障，点击重试"
                        textViewGalleryLoadMoreNoData.visibility = View.VISIBLE
                    }
                }
            }
            return
        }

        val photoItem = getItem(position)
        with(holder.itemView) {
            shimmerLayout.apply {
                setShimmerColor(0x55ffffff)
                setShimmerAngle(0)
                startShimmerAnimation()
            }
            textViewUser.text = photoItem.user
            textViewLikes.text = photoItem.likes.toString()
            textViewFavorites.text = photoItem.favorites.toString()
            imageView.layoutParams.height = photoItem.photoHeight
        }

        Glide.with(holder.itemView)
            .load(photoItem.smallPhoto)
            .placeholder(R.drawable.ic_photo_black_24dp)
            .listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable?,
                    model: Any?,
                    target: Target<Drawable>?,
                    dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false.also { holder.itemView.shimmerLayout?.stopShimmerAnimation() }
                }

            })
            .into(holder.itemView.imageView)
    }

}

class GalleryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)